class LRUCache {
public:
    struct Node {
        Node() : val(0), next(nullptr) {}
        Node(int val) : val(val), next(nullptr) {}
        int val;
        Node *next;
    };
    unordered_map<int, int> map;
    Node *head = new Node();
    int capacity;

    LRUCache(int capacity) {
        this->capacity = capacity;
    }
    
    int get(int key) {
        if (map.count(key) == 0) return -1;
        Node *pre = head;
        Node *node = head->next;
        while (node != nullptr) {
            if (node->val == key) {
                Node *t = node;
                pre->next = node->next;
                t->next = head->next;
                head->next = t;
                break;
            }
            pre = node;
            node = node->next;
        }

        return map[key];
    }
    
    void put(int key, int value) {
        if (map.count(key) != 0) {
            map[key] = value;
            get(key);
            return ;
        }
        if (map.size() == capacity) {
            Node *pre = head;
            Node *node = head->next;
            int dKey = node->val;
           
            while (node->next != nullptr) {
                pre = node;
                
                node = node->next;
                dKey = node->val;
               
            }
            delete(node);
            pre->next = nullptr;
           
            map.erase(dKey);

        }
        if (map.size() < capacity) {
            Node *node = new Node(key);
            node->next = head->next;
            head->next = node;
        }
        map[key] = value;

    }
};

/**
 * Your LRUCache object will be instantiated and called as such:
 * LRUCache* obj = new LRUCache(capacity);
 * int param_1 = obj->get(key);
 * obj->put(key,value);
 */
